import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout'

import store from '../store/index'

Vue.use(VueRouter)

let routes = [
  // {
  //   path: '/login',
  //   name: 'login',
  //   component: () => import('@/views/Login')
  // },
  // {
  //   path: '*',
  //   name: '404',
  //   component: () => import('@/views/Error/404')
  // }
]

const whiteList = ['login', '404']
if (store.state.menuList.length) {
  routes = routes.concat(store.state.menuList)
}

routes.forEach(el => {
  if (!whiteList.includes(el.name)) {
    el.component = Layout
  }
})
console.log(routes)
const router = new VueRouter({
  routes
})

router.addRoutes([...routes])

const hasLogin = () => {
  const data = JSON.parse(localStorage.getItem('vuex'))
  return data
}

router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    if (!hasLogin()) {
      next('/login')
    } else {
      next()
    }
  } else {
    console.log(router)
    next()
  }
})

export default router
